package com.hand.wfive.activity.picker

import android.content.Context
import android.content.Intent
import android.webkit.WebView
import android.webkit.WebViewClient
import com.doris.word.html.WordToHtml
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.entity.Params
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.view.MsgDialog
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_picker_preview_word.*
import kotlin.concurrent.thread

class PreviewWordActivity : BasePreviewActivity() {

    companion object {
        fun showIntent(context: Context, path: String): Intent {
            val intent = Intent(context, PreviewWordActivity::class.java)
            intent.putExtra(Params.path, path)
            return intent
        }
    }

    private var mHtmlPath = ""

    private var mCover = false
    private var mOldScale = 0f

    private var mDefaultScale = 0f
    private var mNewScale = mDefaultScale

    override fun setContentViewBefore() {
        WebView.enableSlowWholeDocumentDraw()
    }

    override fun getContentViewId() = R.layout.activity_picker_preview_word

    override fun init() {
        super.init()

        val settings = webView.settings
        settings.allowFileAccess = true
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.builtInZoomControls = true
        settings.displayZoomControls = false
        settings.setSupportZoom(true)

        webView.webViewClient = object : WebViewClient() {
            override fun onScaleChanged(view: WebView?, oldScale: Float, newScale: Float) {
                super.onScaleChanged(view, oldScale, newScale)
                if (mDefaultScale == 0f) mDefaultScale = newScale
                mOldScale = oldScale
                mNewScale = newScale
                if (mCover) loadCover()
            }
        }
    }

    override fun onPreviewFile() {
        showLoadingTipC()
        Observable.create<String> {
            mHtmlPath = WordToHtml.toHtml(mPath)
            it.onNext(mHtmlPath)
            it.onComplete()
        }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                dismissTip()
                if (it.isEmpty()){
                    showNormalTip("加载失败，暂不支持此预览文件\n请检查文件是否有特殊格式")
                }else{
                    webView.loadUrl("file://${it}")
                }

            },{
                showNormalTip("加载失败，暂不支持此预览文件\n请检查文件是否有特殊格式")
            })
//        thread {
//            mHtmlPath = WordToHtml.toHtml(mPath)
//            runOnUiThread {
//                dismissTip()
//                if (mHtmlPath.isEmpty()) {
//                    showNormalTip("加载失败，暂不支持此预览文件\n请检查文件是否有特殊格式")
//                } else {
//                    webView.loadUrl("file://${mHtmlPath}")
//                }
//            }
//        }
    }

    override fun getUploadFileType() = Params.fileTypeWord

    override fun onUploadFile() {
        if (mHtmlPath.isNotEmpty()) {
            // 直接获取webview bitmap 图片会模糊
            // 如果当前缩放小于2倍则放大2倍
            if (mNewScale < 2f || mNewScale > 4f) {
                mCover = true
                webView.setInitialScale(200)
            } else loadCover()
        } else MsgDialog(
            mContext, "提示", "文件预览失败，上传后暂不能签名，确定继续上传吗？"
        ) {
            if (it == 1) uploadFile()
        }.show()
    }

    private fun loadCover() {
        val width =
            if (mDefaultScale != mNewScale) (webView.width * mNewScale / mDefaultScale + 0.5).toInt()
            else webView.width
        val height = (webView.contentHeight * mNewScale + 0.5).toInt()
        showLoadingTipC()
        thread {
            mFileModel.coverPath = ImageUtils.saveBitmapJPG(
                mContext, ImageUtils.getWebViewBitmap(webView, width, height),
                App.getContext().cacheTempPath
            )
            var name = mFileModel.fileName.replace(",", "")
            name = name.substring(0, name.lastIndexOf("."))
            mFileModel.coverFileId = "${UserManager.getInstance().userId}/file/${
                System.currentTimeMillis()
            }cover_${name}.jpg"
            runOnUiThread { uploadFile() }
        }
    }

    override fun onUploadFileFailure() {
        super.onUploadFileFailure()
        mCover = false
        webView.setInitialScale((mOldScale * 100).toInt())
    }
}